/*
# Rouleur Log - A log for cyclists.
# Copyright (C) 2006  Edward Copony (ecopony@gmail.com)
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
package com.blazingredfireball.rouleurlog.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.blazingredfireball.rouleurlog.business.BikeDelegate;
	import com.blazingredfireball.rouleurlog.model.RouleurlogModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import flash.events.SQLEvent;
	import flash.data.SQLResult;
	import com.blazingredfireball.rouleurlog.vo.BikeVO;

	public class GetBikesCommand extends BaseCommand implements ICommand, IResponder
	{
		private var model:RouleurlogModelLocator = RouleurlogModelLocator.getInstance();
		
		public function execute(event:CairngormEvent):void
		{
		  var delegate:BikeDelegate = new BikeDelegate(this);    
		  delegate.getBikes();
		}
		
		/**
		 * Don't feel good about having knowledge of the result set here. Check 
		 * out AIRCairngorm's approach for wrapping up that knowledge.
		 * 
		 */
		public function result(data:Object):void
		{
		  var sqlEvent:SQLEvent = data as SQLEvent;
		  var result:SQLResult = sqlEvent.target.getResult();
			
			if (result.data != null)
      {
        var bikes:ArrayCollection = new ArrayCollection();
        var bike:BikeVO = null;
            
        for (var i:int = 0; i < result.data.length; i++)
        {
          bike = new BikeVO();
          bike.id = result.data[i].id;
          bike.name = result.data[i].name;
          bike.description = result.data[i].description;
          bike.created_on = new Date(result.data[i].created_on);
          bike.updated_on = new Date(result.data[i].updated_on);
          bikes.addItem(bike);  
        }
        model.bikes = bikes;      
      }
		}
		
		public function fault(info:Object):void
		{
		  if (model.databaseInitialized) Alert.show("Bikes could not be retrieved!");
		}
	}
}